<template>
	<view>
		<u-sticky bgColor="#fff">
			<u-tabs :list="tabs" @click="tabClick" :activeStyle="activeStyle" lineColor="#675f91" :current="current">
				<!-- <view slot="right" class="flex mr15" @tap="nav('/food/food?status='+status+'&id='+id)">
					<view class="text-primary">
						窗口明细
					</view>
					<u-icon name="arrow-right" color="#999999" size="14"></u-icon>
				</view> -->
			</u-tabs>
			<u-line></u-line>
		</u-sticky>
		<!-- current == 0 -->
		<view class="" v-if="current == 0">
			<view class="bgw">
				<view class="text-gray font-24 flex bg-gray">
					<view class="flex-1 col-item" style="">
						食材 单价
					</view>
					<view class="col-item text-center" style="width: 200rpx;">
						数量 
						<!-- 费用 -->
					</view>
					<view class="flex-1 col-item text-right" style="">
						<text style="padding-right: 30rpx;">供应商</text>
					</view>
				</view>
				<u-line></u-line>
				<template v-for="(v,i) in mm_list">
					<view class="flex">
						<view class="flex-1 col-item" style="">
							<view class="font-bold">
								{{v.material_id_name}}
							</view>
							<view class="blank10"></view>
							<view class="flex">
								<view class="text-gray">
									单价：
								</view>
								<view>
									{{v.purchase_unit_price|formatPrice}}元/{{v.purchase_unit_id_name}}
								</view>
							</view>
						</view>
						<view class="col-item" style="width: 200rpx;">
							<view class="text-center" style="white-space: nowrap;">
								{{v.purchase_unit_qty|formatPrice}}{{v.purchase_unit_id_name}}
							</view>
							<!-- <view class="blank10"></view>
							<view class="">
								{{v.purchase_cost|formatPrice}}元
							</view> -->
						</view>
						<view class="flex-1 col-item" style="">
							<view :data-name="i" @click="openMsupplierPicker">
								<view class="blank20"></view>
								<view class="flex">
									<view class="text-light-gray text-right flex-1" v-if="!v.supplier_id_name">
										请选择
									</view>
									<view class="text-right flex-1" v-else>
										{{v.supplier_id_name}}
									</view>
									<u-icon name="arrow-right"></u-icon>
								</view>
								<view class="blank20"></view>
							</view>
						</view>
					</view>
					<!-- <u-col span="3" @click="purchase_first_to_picker(i)">
							<view class="blank20"></view>
							<view class="flex">
								<view class="flex-1 text-right mr10">
									<template v-for="p in purchase_first_to_list[0]">
										<text v-if="v.purchase_first_to == p.id">
											{{p.label}}
										</text>
									</template>
								</view>
								<u-icon name="arrow-down" color="#999999"></u-icon>
							</view>
							<view class="blank20"></view>
						</u-col> -->
					<u-line dashed></u-line>
				</template>
				<view class="col-item">
					<view class="flex">
						<view class="text-gray">采购费用：</view>
						<view class="font-bold">{{purchase_cost | formatPrice}}</view>
					</view>
				</view>
			</view>
			<view class="blank30"></view>
			<!-- note -->
			<view class="bgw wrapper">
				<view class="blank30"></view>
				<u--textarea style="padding: 0;" border="none" v-model="note" placeholder="请输入内容" :count="true"></u--textarea>
				<view class="blank20"></view>
				<view class="text-red">
					成本比例超标，建议填写原因。
				</view>
				<view class="blank20"></view>
			</view>
			<!-- note end -->
		</view>
		<!-- current == 0 end-->
		<!-- 销售预测 -->
		<view class="" v-if="current == 1">
			<!-- 份数填写 -->
			<view class="bgw wrapper">
				<view class="blank20"></view>
				<view class="text-gray font-24">
					<u-row>
						<u-col span="4" align="center">
							档口 单价
						</u-col>
						<u-col span="3" align="center">
							总额
						</u-col>
						<u-col span="5" align="center">
							份数
						</u-col>
					</u-row>
				</view>
				<view class="blank20"></view>
				<u-line></u-line>
				<template v-for="(v,i) in cus_sub_category">
					<view class="blank20"></view>
					<u-row>
						<u-col span="4">
							<view class="font-bold">
								{{v.name}}
							</view>
							<view class="blank10"></view>
							<view class="flex">
								<view class="text-gray">
									单价：
								</view>
								<view>
									5元/分
								</view>
							</view>
						</u-col>
						<u-col span="3">
							<view class="text-center">
								<text class="font-bold">800</text>元
							</view>
						</u-col>
						<u-col span="5">
							<view class="flex justify-center">
								<u-number-box buttonSize="24" v-model="valueObj[v.id]" @change="valChange"></u-number-box>
							</view>
						</u-col>
					</u-row>
					<view class="blank20"></view>
					<u-line dashed></u-line>
				</template>
				<view class="blank20"></view>
				<view class="">
					<u-row>
						<u-col span="4" align="center">
							<view class="text-gray">
								汇总
							</view>
						</u-col>
						<u-col span="3" align="center">
							<view class="text-center">
								<text class="font-bold">800</text>元
							</view>
						</u-col>
						<u-col span="5" align="center">
							<view class="text-center">
								<text class="font-bold">900</text>
							</view>
						</u-col>
					</u-row>
				</view>
				<view class="blank20"></view>

			</view>
			<!-- 份数填写end -->

		</view>
		<!-- 销售预测 end -->
		<!-- current == 1-->
		<view class="" v-if="current == 2">
			<view class="bgw">
				<view class="blank20"></view>
				<template v-for="v in 10">
					<u-row justify="space-between" gutter="3">
						<template v-for="col in tabs[current].tableHd">
							<u-col :span="col.span">
								<view class="text-center" :class="col.title == '比例'?'text-red':''">
									{{col.default}}
								</view>
							</u-col>
						</template>
					</u-row>
					<u-line dashed margin="10rpx 0"></u-line>
				</template>
				<u-row justify="space-between" gutter="3">
					<template v-for="(col,i) in tabs[current].tableHd">
						<u-col :span="col.span">
							<view class="text-center  text-gray" v-if="i == 0">
								汇总
							</view>
							<view class="text-center" v-else>
								{{col.default}}
							</view>
						</u-col>
					</template>
				</u-row>
				<view class="blank20"></view>
			</view>
			<view class="wrapper" v-if="status == 's0_draft'">
				<view class="blank20"></view>
				<view class="text-red">
					成本比例超标，建议【提交】时填写原因。
				</view>
				<view class="blank20"></view>
			</view>
		</view>
		<view class="blank30"></view>

		<template v-if="current == 0">
			<view class="blank"></view>
			<view class="wrapper fixed-bottom bg-gray">
				<view class="blank30"></view>
				<u-button type="primary" @click="save">提交</u-button>
				<view class="blank30"></view>
			</view>
		</template>

		<u-modal :show="modalShow" title="提示" :content='modalContent' :showCancelButton="true" confirmColor="#675f91"
			@confirm="modalConfirm" @cancel="modalCancel" confirmText="下单"></u-modal>

		<msupplierPicker :show="msupplierPickerShow" :msupplier="msupplier" @confirm="msupplierPickerConfirm"
			@cancel="msupplierPickerCancel" v-if="msupplier.length>0"></msupplierPicker>

	</view>
</template>

<script>
	import purchaseInfo from '@/pagesA/components/purchase-info.vue';
	import msupplierPicker from '@/pagesA/components/msupplier-picker.vue';
	import {
		purchase_request_record,
		purchase_record_detail,
		purchase_record_approve,
		chef_direct_place_po,
		purchase_request_draft,
		purchase_record_handin,
		purchase_request_edit,
		material_create_edit
	} from '@/common/api.js';

	let today = new Date();
	let date = new Date(today.getTime() + (24 * 60 * 60 * 1000 * 1)); //明天
	let year_month_day = `${date.getFullYear()}` + `-` + `${date.getMonth()+1}`.padStart(2, '0') + `-` +
		`${date.getDate()}`.padStart(2, '0');

	export default {
		components: {
			purchaseInfo,
			msupplierPicker
		},
		data() {
			return {
				saleFlag: true,
				checkboxValue: [],
				id: '',
				status: '',
				status1: '',
				note: '',
				titleStyle: {
					color: '#ffffff'
				},
				bgColor: '#675f91',
				activeStyle: {
					color: '#675f91'
				},
				tabs: [{
						name: '汇总',
					},
					{
						name: '销售预测',
					},
					{
						name: '成本比例',
						tableHd: [{
								title: '分类',
								default: '蔬菜',
								span: 4
							},
							{
								title: '金额',
								default: '200',
								span: 2
							},
							{
								title: '比例',
								default: '25.0%',
								span: 2,
							},
							{
								title: '标准',
								default: '23%',
								span: 2
							},
							{
								title: '本月度',
								default: '0%',
								span: 2
							},
						]
					}
				],
				current: 0,
				list: [],
				listHead: [],
				page: 0,
				loadstatus: 'nomore',
				loadingText: '努力加载中',
				loadmoreText: '轻轻上拉',
				nomoreText: '没有了',
				isManager: false,
				modalContent: '',
				modalShow: false,

				sumed_pr_record: [], //食材汇总
				mm_list: [],
				month_cost_ratio: [],

				need_day: year_month_day,
				cus_sub_category: [],
				material_item: [],
				material_obj: {},
				purchase_record_list: [],
				forecast_list: [],
				valueObj: {},
				isShowCusTabs: false,
				detail: {},
				approve_status_obj: {
					s0_pending: '草稿',
					s1_apply: '请审批',
					s2_approve: '同意',
					s3_reject: '驳回',
				},
				steps: [],
				value: '',
				supplier_id_list: [],
				picker_value: [],
				purchase_first_to_picker_show: false,
				purchase_first_to_list: [
					[{
							label: '审批',
							id: "to_purchase"
						},
						{
							label: '直接下单',
							id: "to_supplier"
						},
					]
				],
				purchase_cost: 0,
				msupplier: [],
				msupplierObj: {},
				msupplierPickerShow: false,
				msupplierPickerKey: '',
			}
		},
		methods: {
			msupplierPickerCancel(e) {
				this.msupplierPickerShow = false;
			},
			msupplierPickerConfirm(e) {
				let key = this.msupplierPickerKey;
				this.msupplierPickerShow = false;
				this.mm_list[key].supplier_id = e.id;
				this.mm_list[key].supplier_id_name = e.label;
			},
			openMsupplierPicker(e) {
				let key = e.currentTarget.dataset.name;
				this.msupplierPickerKey = Number(key);
				this.msupplierPickerShow = true;
			},
			// 弃用
			bindPicker(e) {
				let key = e.currentTarget.dataset.name;
				let index = e.detail.value;
				this.picker_value[key] = index;
				// console.log(key);
				this.mm_list[key].supplier_id = this.supplier_id_list[index].id;
				this.mm_list[key].supplier_id_name = this.supplier_id_list[index].label;
			},

			purchase_first_to_picker(i) {
				// console.log(v);
				// this.purchase_first_to_picker_show = true;
				this.pickerColumns = this.purchase_first_to_list;
				this.pickerData = {
					index: i,
					key: 'purchase_first_to'
				};
				this.pickerShow = true;
			},
			valChange() {

			},
			modalConfirm() {
				this.modalShow = false;
				uni.$u.toast('已成功下单');
				// this.foodCurrent = 3;
			},
			modalCancel() {
				this.modalShow = false;
			},
			order() {

			},
			refuse() {
				// uni.$u.toast('操作成功');
				this.purchase_record_approve(false);
			},
			allow() {
				// this.modalContent = '已审批成功，是否将‘土豆、西红柿’等5种食材下单？';
				// this.modalShow = true;
				this.purchase_record_approve(true);
			},
			purchase_record_approve(is_approve) {
				uni.showLoading({
					title: '加载中'
				});
				purchase_record_approve({
					pr_id: this.id,
					is_approve: is_approve,
					note: this.value
				}).then((res) => {
					uni.$u.toast('操作成功');
					setTimeout(() => {
						this.getData();
					}, 2000)

				}).catch(() => {

				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},
			checkboxChange(n) {
				console.log('change', n);
			},
			tabClick(e) {
				// console.log(e);
				// console.log(this.current);
				this.current = e.index;
			},
			foodTabClick(e) {
				this.foodCurrent = e.index;
			},
			set_forecast_list() {
				let forecast_list = [];
				for (let id in this.valueObj) {
					forecast_list.push({
						cus_sub_id: id,
						sales_qty: this.valueObj[id]
					})
				}
				this.forecast_list = forecast_list;
				let id = this.id;
				uni.setStorage({
					key: 'forecast_list_' + id,
					data: forecast_list,
					success: function() {
						// console.log('success');
					}
				});
			},
			save() {
				// uni.$u.toast('未对接');
				// return;

				// this.set_forecast_list();
				let mm_list = this.mm_list.map(v => {
					return {
						'material_id': v.material_id,
						'purchase_unit_price': v.purchase_unit_price,
						'purchase_unit_id': v.purchase_unit_id,
						'purchase_unit_qty': v.purchase_unit_qty,
						'need_date': v.need_date,
						'supplier_id': v.supplier_id,
						'mbatch_int': v.mbatch_int,
						'pr_id':v.pr_id,
						'pr_sumed_mm_id':v.pr_sumed_mm_id
					}
				})
				uni.showLoading({
					title: '加载中'
				});
				purchase_record_handin({
					mm_list: mm_list,
					day: this.need_day
					// pr_id: this.id,
					// purchase_record_list: this.purchase_record_list,
					// forecast_list: this.forecast_list,
					// day: this.need_day,
					// note: this.note,
				}).then((res) => {
					uni.$u.toast('操作成功');
					setTimeout(() => {
						uni.$emit('refresh_index');
						if (this.id == 0) {
							uni.navigateBack({
								delta: 2
							});
						} else {
							uni.navigateBack({
								delta: 1
							});
						}
					}, 2000)

				}).catch(() => {


				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})


				// setTimeout(() => {
				// 	uni.$u.route({
				// 		type: 'navigateBack'
				// 	})
				// }, 1500);
			},
			getData() {
				uni.showLoading({
					title: '加载中'
				});
				let pr_id = this.id;

				purchase_request_edit({
					pr_id: pr_id,
					day: this.need_day
				}).then((res) => {
					let {
						msupplier,
						cus_sub_category
					} = res.result;
					let supplier_id_list = msupplier.map(v => {
						return {
							label: v.supplier_nick_name,
							id: v.id
						}
					});
					this.supplier_id_list = supplier_id_list;
					this.cus_sub_category = cus_sub_category;
					this.valueObj = {};
					cus_sub_category.forEach(v => {
						this.valueObj[v.id] = 1
					});
				}).catch(() => {

				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})

				purchase_request_record().then((res) => {
					this.detail = res.result.find(v => v.id == pr_id);
					this.status = this.detail['状态'];
					if (this.status != 's0_draft') {
						this.nav('/purchaseDetail/purchaseDetail?id=' + pr_id, 'redirect');
						return;
					}
				}).catch(() => {

				}).finally(() => {

				})
				purchase_record_detail({
					pr_id: pr_id
				}).then((res) => {
					// this.list = res.result;
					let {
						sumed_pr_record,
						month_cost_ratio
					} = res.result;
					sumed_pr_record.forEach(v => {
						v.supplier_id_name = v.supplier_id[1];
						v.supplier_id = v.supplier_id[0];
						v.purchase_first_to = 'to_supplier';
					})
					this.sumed_pr_record = sumed_pr_record;
					this.month_cost_ratio = month_cost_ratio;
				}).catch(() => {

				}).finally(() => {

				})

			},
			getData0() {
				try {
					const value = uni.getStorageSync('mm_list_0');
					console.log(value);
					let purchase_cost = 0;
					if (value) {
						value.forEach(v => {
							v.material_id_name = v.material_id[1];
							v.material_id = v.material_id[0];
							v.supplier_id_name = v.supplier_id[1];
							v.supplier_id = v.supplier_id[0];
							v.purchase_unit_id_name = v.purchase_unit_id[1];
							v.purchase_unit_id = v.purchase_unit_id[0];
							purchase_cost += v.purchase_cost;
						})
						this.mm_list = value;
						this.purchase_cost = purchase_cost;
						
					}
				} catch (e) {
					uni.$u.toast('汇总食材读取失败');
				}

				uni.showLoading({
					title: '加载中'
				});
				material_create_edit().then((res) => {
					let {
						msupplier
					} = res.result;
					let msupplierObj = {};
					let msupplierOldIdObj = {};
					msupplier.forEach(v => {
						v.msupplier_id = v.id;
						v.id = v.supplier_id[0];
						msupplierObj[v.id] = v;
						msupplierOldIdObj[v.msupplier_id] = v;
					})
					this.msupplier = msupplier;
					this.msupplierObj = msupplierObj;
					// let supplier_id_list = msupplier.map(v => {
					// 	return {
					// 		label: v.supplier_id[1],
					// 		id: v.supplier_id[0]
					// 	}
					// });
					// this.supplier_id_list = supplier_id_list;
					// this.picker_value = [];
					// this.mm_list.forEach(v=>{
					// 	let index = supplier_id_list.findIndex(s=>s.id == v.supplier_id);
					// 	this.picker_value.push(index);
					// })
				}).catch(() => {

				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})


			}
		},
		onLoad(d) {
			this.id = Number(d.id) || 0;

			if (this.id == 0) {
				this.getData0();
			}
			// this.getData();

		},
		onShow() {

		},
		onReady() {

		},
		onPullDownRefresh() {
			// this.getData();
		}
	}
</script>

<style lang="scss" scoped>
	.blank {
		height: calc(60rpx + 40px);
	}

	.btn-refuse {
		height: 90upx;
		line-height: 90upx;
		width: 200upx;
		text-align: center;
		background-color: #E40A0C;
		color: #ffffff;
	}

	.btn-allow {
		height: 90upx;
		line-height: 90upx;
		width: 200upx;
		text-align: center;
		background-color: #00AD2E;
		color: #ffffff;
	}

	.btn-confirm {
		height: 90upx;
		line-height: 90upx;
		width: 200upx;
		text-align: center;
		background-color: #675f91;
		color: #ffffff;
	}

	.col-item {
		padding: 15upx 15upx;
	}
</style>